package com.sky.wsp.license.pkix;

import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.x509.X509V3CertificateGenerator;

import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.Provider.Service;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.KeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * https://blog.csdn.net/qq_34823185/article/details/134303239
 */
public class PKCS12KeyStoreExample {
    private static final String P1_KEYSTORE = "p1_keystore.p12";
    private static final String PWD = "pwd123";
    private static final String ORG_1 = "org1";
    private static final String ORG_2 = "org2";

    public static void main(String[] args) {
//        gen();
         genP12();
//        testCert();

    }

    public static void testCert() {
        String base64Public = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiDtyBZmFd8AxQVJN9jMI9H5CaFwKjq4m14dxc+njKvg6D8AWWpkCdhajcGZ1JrDua/GXKZPuLHR/1Rt6QyIUjMNlKZhUZrNoxKOVLa4Awa7VmR+LDCWHUvuE9G1o6ZWjlS7fvw2QBYZ1nz9t6x4d+tlcMrZ5GV1we41uE1ZUDGDe0a5UIlgf3RG2quLPtuVhfKk1fMdfPYWe5M12Tt0zkPOEt63909/wqq6fiHVoKeDrfL35dCNDwT6sFCrnRNDpYwh7XhumtWuD7Q2akFAj8jCAJ1DHg0KiGkRRILN47pRdP7oZfDd//P4Qt9D+L2fQkbWf+qQUAYSWFyKWby9EqQIDAQAB";
        String base64Cert = "MIICqzCCAZOgAwIBAgIBATANBgkqhkiG9w0BAQsFADAZMRcwFQYDVQQDDA5NeSBDZXJ0aWZpY2F0ZTAeFw0yNDA2MjEwMTAzNTFaFw0yNTA2MjEwMTAzNTFaMBkxFzAVBgNVBAMMDk15IENlcnRpZmljYXRlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiDtyBZmFd8AxQVJN9jMI9H5CaFwKjq4m14dxc+njKvg6D8AWWpkCdhajcGZ1JrDua/GXKZPuLHR/1Rt6QyIUjMNlKZhUZrNoxKOVLa4Awa7VmR+LDCWHUvuE9G1o6ZWjlS7fvw2QBYZ1nz9t6x4d+tlcMrZ5GV1we41uE1ZUDGDe0a5UIlgf3RG2quLPtuVhfKk1fMdfPYWe5M12Tt0zkPOEt63909/wqq6fiHVoKeDrfL35dCNDwT6sFCrnRNDpYwh7XhumtWuD7Q2akFAj8jCAJ1DHg0KiGkRRILN47pRdP7oZfDd//P4Qt9D+L2fQkbWf+qQUAYSWFyKWby9EqQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAa0ofTsY4Xia+r/h1fHpnRKoKCPqVLaRFjxtCpwM+y/cZ1elz7oasXHmKPP0Mfy7TaNQRpg770AmB8YFWBqq5nXOkopo01D3gs8uQ9AYx16T7jrw7wr2ccPgIWgkBc2msYvfLTU0bV1S+QKkqFoH43QLkxqRsREhOa98VsZRwfq/M5l/zCawCFZ8UezYBNrZ5QDP0uNB9GPyvmXF9rjZ4vlcJc7J+rHgNxLWF8AdbXdIp6x1WmhCQhEXTeqdYv36ZmtbRN1kL/C3PRcLvFyoYa667hVFiRSG8ZXfNmRfC52OFdC0dmsf84l7A4l2bNN+x/hpc8MkeYjhEAPmGGUwnI";
        try {
            byte[] decodePublic = Base64.decode(base64Public);
            KeySpec publicKeySpec = new X509EncodedKeySpec(decodePublic);
            KeyFactory instance = KeyFactory.getInstance("RSA");
            PublicKey publicKey = instance.generatePublic(publicKeySpec);

            // 生成 X.509 证书
            byte[] decodeCert = Base64.decode(base64Cert);
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(decodeCert));
            PublicKey certPublicKey = certificate.getPublicKey();
            boolean equals = publicKey.equals(certPublicKey);
            System.out.printf(equals ? "equals" : "not equals\n");

            certificate.checkValidity();
            System.out.println("certificate in validity!");

            certificate.verify(publicKey);
            System.out.println("certificate verify success!");

            String issuer = certificate.getIssuerDN().getName();
            Date notBefore = certificate.getNotBefore();
            Date notAfter = certificate.getNotAfter();
            BigInteger serialNumber = certificate.getSerialNumber();

            System.out.printf("cert: %s, %d, %tc, %tc%n", issuer, serialNumber, notBefore, notAfter);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void genP12() {
        try { 
            // 生成密钥对
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            byte[] encodedPrivate = keyPair.getPrivate().getEncoded();
            byte[] encodedPublic = keyPair.getPublic().getEncoded();

            String base64Private = Base64.toBase64String(encodedPrivate);
            System.out.println(base64Private);
            String base64Public = Base64.toBase64String(encodedPublic);
            System.out.println(base64Public);

            byte[] decodePublic = Base64.decode(base64Public);
            KeyFactory instance = KeyFactory.getInstance("RSA");
            KeySpec publicKeySpec = new X509EncodedKeySpec(decodePublic);
            PublicKey publicKey = instance.generatePublic(publicKeySpec);

            // 生成 X.509 证书
            X509Certificate cert = generateCertificate(keyPair);
            byte[] encodedCert = cert.getEncoded();
            String base64Cert = Base64.toBase64String(encodedCert);
            System.out.println(base64Cert);
            byte[] decodeCert = Base64.decode(base64Cert);

            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(decodeCert));
            certificate.checkValidity();
            certificate.verify(publicKey);


//            // 创建 PKCS12 密钥库
//            KeyStore keyStore = KeyStore.getInstance("PKCS12");
//            keyStore.load(null, null);
//
//            // 将私钥和证书存入密钥库
//            char[] password = PWD.toCharArray();
//            keyStore.setKeyEntry(ORG_1, keyPair.getPrivate(), password, new Certificate[]{cert});
//
//            // 保存密钥库到文件
//            FileOutputStream fos = new FileOutputStream(P1_KEYSTORE);
//            keyStore.store(fos, password);
//            fos.close();

            System.out.println("PKCS12 密钥库已生成！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static X509Certificate generateCertificate(KeyPair keyPair) throws Exception {
        // 生成自签名的 X.509 证书
        X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
        certGenerator.setSerialNumber(BigInteger.valueOf(1));
        certGenerator.setSubjectDN(new X509Principal("CN=My Certificate"));
        certGenerator.setIssuerDN(new X509Principal("CN=My Certificate"));
        certGenerator.setNotBefore(new Date());
        certGenerator.setNotAfter(new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000L));
        certGenerator.setPublicKey(keyPair.getPublic());
        certGenerator.setSignatureAlgorithm("SHA256withRSA");
        return certGenerator.generate(keyPair.getPrivate());
    }
    
    public static void gen() {
        for (Provider provider : Security.getProviders()) {
        	Set<Service> set= provider.getServices();
        	for (Iterator iterator = set.iterator(); iterator.hasNext();) {
				Service service = (Service) iterator.next();
				if(service.getAlgorithm().contains("SHA256")) {
					System.out.println(service.getAlgorithm());
				}
			}
            
        }
    }
}
